package br.com.srv.util;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * Description: Classe auxiliar para tratamento de Cookies.
 * </p>
 * 
 */

public class CookieHelper {
	public static Cookie getCookie(Cookie[] cookies, String name) throws Exception {
		if (cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				if (cookies[i].getName().equals(name)) {
					return cookies[i];
				}
			}
		}
		return null;
	}

	public static Cookie getCookie(HttpServletRequest request, String name) throws Exception {
		return getCookie(request.getCookies(), name);
	}

	public static void checkCookie(HttpServletRequest request, HttpServletResponse response, Map form, String name, String value) throws Exception {
		if (getCookie(request.getCookies(), name) == null) {
			// Criar cookie com valor default
			Cookie cookie = new Cookie(name, value);
			cookie.setMaxAge(1000000000);
			response.addCookie(cookie);
			form.put(name, new Long(value));
		} else {
			// Ler valor do cookie
			Cookie cookie = getCookie(request.getCookies(), name);
			form.put(name, new Long(cookie.getValue()));
		}
	}
}
